package com.gzhryc.shared_device.oem.h5.agent.mng.controllers;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;

import com.gzhryc.common.StringTools;
import com.gzhryc.common.data.dto.AjaxResult;
import com.gzhryc.common.data.dto.echars.Axis;
import com.gzhryc.common.data.dto.echars.EchartsOption;
import com.gzhryc.common.data.dto.echars.SeriesItem;
import com.gzhryc.common.data.dto.echars.Title;
import com.gzhryc.common.data.dto.echars.Tooltip;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.common.secruity.VerifyCodeTools;
import com.gzhryc.common.secruity.VerifyCodeTools.VerifyCode;
import com.gzhryc.servlet.DtoConstants;
import com.gzhryc.servlet.WebUtils;
import com.gzhryc.servlet.annotation.Route;
import com.gzhryc.shared_device.common.device.services.DeviceService;
import com.gzhryc.shared_device.common.device.services.dto.DeviceSearch;
import com.gzhryc.shared_device.oem.code.BaseConstants;
import com.gzhryc.shared_device.oem.code.agent.dao.db.Agent;
import com.gzhryc.shared_device.oem.code.agent.services.AgentRelationService;
import com.gzhryc.shared_device.oem.code.agent.services.AgentService;
import com.gzhryc.shared_device.oem.code.agent.services.AgentTypeMenuRelService;
import com.gzhryc.shared_device.oem.code.agent.services.AgentTypeRelService;
import com.gzhryc.shared_device.oem.code.place.services.PlacePhysicalStoreService;
import com.gzhryc.shared_device.oem.code.place.services.dto.PlacePhysicalStoreSearch;
import com.gzhryc.shared_device.oem.code.statistics.dao.db.UserProfitDayStatistics;
import com.gzhryc.shared_device.oem.code.statistics.dao.models.UserProfitSumMoneyData;
import com.gzhryc.shared_device.oem.code.statistics.services.UserProfitDayStatisticsService;
import com.gzhryc.shared_device.oem.code.statistics.services.dao.UserProfitDayStatisticsSearch;
import com.gzhryc.shared_device.oem.code.user.dao.db.User;
import com.gzhryc.shared_device.oem.code.user.dao.db.UserWallet;
import com.gzhryc.shared_device.oem.code.user.services.UserService;
import com.gzhryc.shared_device.oem.code.user.services.UserWalletService;
import com.gzhryc.shared_device.oem.h5.agent.mng.WebConstants;
import com.gzhryc.shared_device.oem.h5.agent.mng.dto.OrderChartsData;
import com.gzhryc.system.SysConstants;
import com.gzhryc.system.dto.MenuData;

public class IndexController {

	static Logger log = Logger.getLogger(IndexController.class);
	
	@Route(value={"/index.html","/"})
	public String index(HttpServletRequest request){
		return "/index.html";
	}
	
	@Route(value={"/console.html"})
	public String main(HttpServletRequest request) {
		User loginUser = WebUtils.getAttribute(request, WebConstants.LOGIN_USER, User.class);
		if (loginUser != null) {
			Date currentDate = new Date();

			String yearNum = DateFormatUtils.format(currentDate,"yyyy");
			request.setAttribute("yearNum",yearNum);

			UserProfitDayStatistics userProfitDayStatistics = UserProfitDayStatisticsService.self(currentDate).getByKeys(loginUser.getId(),currentDate);
			if(userProfitDayStatistics == null){
				userProfitDayStatistics = new UserProfitDayStatistics();
				userProfitDayStatistics.setIncomeCount(0);
			}
			request.setAttribute("todayStatistics",userProfitDayStatistics);

			UserProfitSumMoneyData userProfitSumMoneyData = UserProfitDayStatisticsService.self(currentDate).sumByUser(loginUser.getId());
			request.setAttribute("yearStatistics",userProfitSumMoneyData);

			DeviceSearch deviceSearch = new DeviceSearch();
			deviceSearch.setUserId(loginUser.getId());
			Long deviceCount = DeviceService.self().countBySearch(deviceSearch);

			deviceSearch.setDeploy(true);
			Long deployDeviceCount = DeviceService.self().countBySearch(deviceSearch);

			PlacePhysicalStoreSearch search = new PlacePhysicalStoreSearch();
			search.setUserId(loginUser.getId());
			Long placeCount = PlacePhysicalStoreService.self().countJoinBySearch(search);

			Long userCount = AgentRelationService.self().countJoinByUserId(loginUser.getId());

			request.setAttribute("deviceCount",deviceCount);
			request.setAttribute("deployDeviceCount",deployDeviceCount);
			request.setAttribute("placeCount",placeCount);
			request.setAttribute("userCount",userCount);

			List<UserWallet> userWalletList = UserWalletService.self().findJoinByUserId(loginUser.getId());
			if(userWalletList != null){
				request.setAttribute("userWalletList",userWalletList);
			}
		}
		return "/console.html";
	}

	@Route(value={"/console/order/charts.data"})
	public OrderChartsData getConsoleOrderCharts(HttpServletRequest request){
		OrderChartsData result = new OrderChartsData(DtoConstants.NULL_DATA,"暂无数据");
		User loginUser = WebUtils.getAttribute(request, WebConstants.LOGIN_USER, User.class);
		if (loginUser != null) {
			Date endDate = new Date();
			Date startDate = DateUtils.addDays(endDate, -20);

			UserProfitDayStatisticsSearch search = new UserProfitDayStatisticsSearch();
			search.setUserId(loginUser.getId());
			search.setStartDate(startDate);
			search.setEndDate(endDate);
			List<UserProfitDayStatistics> userProfitDayStatisticsList = UserProfitDayStatisticsService.self().findBySearch(search,1,20);

			EchartsOption option = new EchartsOption();
			option.setTitle(new Title());
			option.getTitle().setText("近20日营业额趋势");
			option.setTooltip(new Tooltip());

			option.setxAxis(new Axis());
			option.getxAxis().setType(Axis.Type_Category);
			option.getxAxis().setData(new ArrayList<>());

			option.setyAxis(new Axis());
			option.getyAxis().setType(Axis.Type_Value);

			option.setSeries(new ArrayList<>());
			SeriesItem item = new SeriesItem();
			item.setName("营业额");
			item.setType(SeriesItem.Type_Line);
			item.setSmooth(true);
			item.setItemStyle(new SeriesItem.ItemStyle());
			item.getItemStyle().setNormal(new SeriesItem.ItemStyleNormal());
			item.getItemStyle().getNormal().setAreaStyle(new SeriesItem.AreaStyle());
			item.setData(new ArrayList<>());


			for (int i = 0; i <= 21; i++) {
				Date temp = DateUtils.addDays(startDate, i);
				String dayDate = DateFormatUtils.format(temp, "yyyyMMdd");

				option.getxAxis().getData().add(DateFormatUtils.format(temp, "MM-dd"));

				boolean flag = true;
				if (userProfitDayStatisticsList != null && userProfitDayStatisticsList.size() > 0) {
					for (UserProfitDayStatistics dayStatistics : userProfitDayStatisticsList) {
						if (dayStatistics.getDayDate().equals(dayDate)) {
							item.getData().add(dayStatistics.getOrderMoneyStr());
							flag = false;
							break;
						}
					}
				}

				if (flag) {
					item.getData().add(0);
				}
			}
			option.getSeries().add(item);

			result.setCode(DtoConstants.SUCCESS, null);
			result.getBody().setOptionList(new ArrayList<>());
			result.getBody().getOptionList().add(option);
		}
		return result;
	}

	@Route(value={"/login.html"},method="GET")
	public String login(){
		return "/login.html";
	}
	
	@Route(value={"/verifyCode.jpeg"})
	public void vie(HttpServletRequest request,HttpServletResponse response,HttpSession session) {
		Integer width = WebUtils.getInteger(request, "w",250);
		Integer height = WebUtils.getInteger(request, "h",50);
		VerifyCode verifyCode = VerifyCodeTools.createImg(width, height, 5);
		if(verifyCode != null) {
			session.setAttribute(SysConstants.SESSION_VERFITY_CODE, verifyCode.getCode());
			WebUtils.exportJPEG(response, verifyCode.getImg());
		}
	}
	
	@Route(value={"/login.do"},method="POST")
	public AjaxResult doLogin(HttpServletRequest request,HttpServletResponse response,HttpSession session){
		AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR,"登陆失败，请检查账号或密码");
		String loginName = request.getParameter("loginName");
		String loginPwd = request.getParameter("loginPwd");
		String vercode = request.getParameter("vercode");
		String remember = request.getParameter("remember");
		
		String verifyCode = WebUtils.getAttribute(session, SysConstants.SESSION_VERFITY_CODE, String.class);
		if(StringUtils.isNotBlank(vercode) && vercode.toUpperCase().equals(verifyCode)){
			if(StringUtils.isNotBlank(loginName) && StringUtils.isNotBlank(loginPwd)){
				try{
					User user = UserService.self().login(loginName, loginPwd);
					if(user != null){
						Agent agent = AgentService.self().getByUserId(user.getId());
						if(agent != null) {
							agent.setUser(user);	//缓存用户信息
							//检查是否有菜单，如果没有配置菜单则不允许登陆
							List<Long> typeIds = AgentTypeRelService.self().findTypeIdsByUserId(agent.getUserId());
							List<MenuData> menuData = AgentTypeMenuRelService.self().findMenuDataByTypeIds(agent.getUserId(),typeIds);
							if(menuData != null && menuData.size() > 0){
								if(StringTools.isNotBlank(remember) && "on".equals(remember)) {
									//默认30天
									Integer time = 30 * 24 * 60 * 60;
									WebUtils.setCookies(request, response, SysConstants.COOKIES_LOGIN_TOKEN, user.getLoginToken(), time);
								}else {
									WebUtils.setCookies(request, response, SysConstants.COOKIES_LOGIN_TOKEN, "", 3);
								}
								
								session.setAttribute(SysConstants.SESSION_LOGIN_MENUS, menuData);
								session.setAttribute(WebConstants.SESSION_LOGIN_AGENT, agent);
								result.setCode(DtoConstants.SUCCESS, null);
							}else{
								result.setMsg("未开启后台管理功能，请联系客服咨询");
							}
						}
					}
				}catch(Exception e){
					result.setMsg(e.getMessage());
				}
			}else{
				result.setMsg("请填写账号或密码");
			}
		}else {
			result.setMsg("验证码不正确");
		}
		return result;
	}
	
	@Route(value={"/logout.do"})
	public AjaxResult logout(HttpServletRequest request,HttpServletResponse response,HttpSession session){
		AjaxResult result = new AjaxResult(DtoConstants.SUCCESS);
		User loginUser = WebUtils.getAttribute(request, WebConstants.LOGIN_USER, User.class);
		if(loginUser != null) {
			UserService.self().logout(loginUser.getId());
		}
		session.invalidate();
		//设置为空
		WebUtils.setCookies(request, response, SysConstants.COOKIES_LOGIN_TOKEN, "", 3);
		return result;
	}
	
	@Route(value={"/about.html"},method="GET")
	public String about(HttpServletRequest request){
		request.setAttribute("version", BaseConstants.VERSION);
		return "/about.html";
	}

}
